/*
	List of book items. Used for Start page, Browse page, Favoriate page, Search page
*/

var OverviewVM = function (funcViewBook) {

	// Variables and localizations of Overview page
	var datacontext = new DataContext(),
	folderID = ko.observable(''),
	list = ko.observableArray([]),
	listNext = ko.observableArray([]),
	listBuff = ko.observableArray([]),
	listPrev = ko.observableArray([]),
	listFavorite = ko.observableArray([]),
    listAnimation = ko.observableArray([]),
	keySearch = ko.observable(),
	isEditing = ko.observable(false),
	isDisplayOverView = ko.observable(false),
	currentFavoriteItem = null,
	isScrolling = false,
	currentPosition = 0,
	title = ko.observable(''),
	currentItem = null,
	areYouSureDelete = getLocalizeText('areYouSureDelete'),
	strEdit = getLocalizeText('edit'),
	strDone = getLocalizeText('done'),
    currentLeft = 0,
    currentTop = 0,
    currentWidth = 0,
    currentHeight = 0,
    currentImg = '',

		// Handle paging in book items list
		applyScrollPager = function (callBackLoadMore) {
			if (myScrollPager != null) {
				myScrollPager.destroy();
				myScrollPager = null;
			}
			myScrollPager = new iScroll('wrapper_scrollpager', {
				hScroll: false,
				hideScrollbar: true,
				onBeforeScrollStart: function (e) {
					var target = e.target;
					while (target.nodeType != 1) target = target.parentNode;
					if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA')
						e.preventDefault();
					// [WP]
					if (isWP) {
						currentPosition = this.y;
						model.overviewVM.isScrolling = false;
					}
				},
				onScrollEnd: function () {
					// [WP]
					if (isWP) {
						if (currentPosition != this.y) {
							model.overviewVM.isScrolling = true;
						} else {
							model.overviewVM.isScrolling = false;
						}
					}
					if (!isScrollByUser) {
						isScrollByUser = true;
						return;
					}
					if (this.y == 0) {
						if (!isLoading) {
							addItemTop();
						}
					} else if (this.maxScrollY == this.y) {
						if (!isLoading) {
							if (callBackLoadMore != undefined) {
								callBackLoadMore();
							}
							addItemBottom();
						}
					}
				}
			});
		},

		// [WP]
		nanoLock = true,
		applyAfterFillDataNano = function () {
			$('.nano').nanoScroller({
				destroy: true
			});
			$('.nano').nanoScroller();
			$('.nano').nanoScroller({
				alwaysVisible: true
			});
			$('.nano').nanoScroller({
				sliderMinHeight: 10
			});
			$('.nano').nanoScroller({
				flash: true
			});
			$('.nano').nanoScroller({
				preventPageScrolling: false
			});
			nanoLock = false;
		},

		applyScrollPagerNano = function (callBackLoadMore) {
			var sync = true;
			/* refresh of new nano scroller */
			applyAfterFillDataNano();
			/* handle scroll to end */
			$('.nano').bind("scrollend", function (e) {

				if (!nanoLock) {
					nanoLock = true;
					$('.nano').nanoScroller({
						preventPageScrolling: true
					});
					if (!isLoading) {
						if (callBackLoadMore != undefined) {
							callBackLoadMore();
						}
						addItemBottom();
					}
				}
			});
		},

		// Search book items: get all books by keyword
		getByKey = function () {
            currentItem = null;
			list([]);
			listNext([]);
			listPrev([]);
			showLoadingDialog();
			isLoading = true;
			title(getLocalizeText("search"));
            var listResult = ko.observableArray([]);
			datacontext.overview.search({
				results: listResult,
				keySearch: keySearch()
			}).done(function () {
				CheckExpireSession(
					listResult,
					true,
					function() {
						getByKey();
					}, 
					function(entityResult) {
                        listNext(entityResult());
						model.cateVM.listnext([]);
						model.childOverviewTmpl('overviewTmpl');
						isDisplayOverView(true);
						model.isShowSearchResult(true);
						model.startpageVM.isDisplayStartPage(false);
						applyScrollPager();
						addToList();
						setTimeout(function applyScroll() {
							myScrollPager.refresh();
						}, 200);
					});
			}).fail(function (e) {
                    CheckExpireSessionErrorCallback(e,
                                                    function(){
                                                    /* session expired */
                                                    getByKey();
                                                    },
                                                    function(){
                                                    /* not expire */
                                                    });
			});
		},

		/*
			Get all book items by category:
			+ item: category
			+ page: index of pager
		*/
		getByCategory = function (item, page) {
			var maxPageNumberTemp = maxPageNumber;
			if (page == undefined || page == 0) {
				page = 0;
				maxPageNumberTemp = maxPageNumber * pageBufferNumber;
				list([]);
				listNext([]);
				listPrev([]);
                // [iOS]
                if (isiOS){
                    var strKey = item.id() + '' + model.cateVM.currentItemId() + model.settingsVM.getLanguageString();
                    if (overviewListFromSubcategory[strKey] != undefined) {
                        var listTemp = ko.observableArray(overviewListFromSubcategory[strKey]);
                        _.each(listTemp(), function (i) {
                               listNext.push(i);
                               });
                        addToList(list, listNext);
                        applyScrollPager(function callBackLoadMore() {
                                         loadOverviewMore(item);
                                         });
                        // setTimeout(function applyScroll(){myScroll.refresh();}, 5000);
                        return;
                    }
                }
				showLoadingDialog();
			}
			currentItem = item;
			isLoading = true;
			listBuff([]);
			title(item.caption());

			var listResult = ko.observableArray([]);
			/*
				Load book items and store to local:
				+ File per category and paging
				* First page: get (maxPageNumber * pageBufferNumber) items
				+ listBuff: current return list
			*/
			datacontext.overview.getByCategory({
				results: listResult,
				key: 'saveFilesearch_' + model.settingsVM.getLanguageString() + '_' + item.id() + '_' + page + '_' + maxPageNumber,
				page: page,
				maxPage: maxPageNumberTemp,
				categoryId: item.id(),
				callbackFunc: function () {
                    if (listResult().length > 0){
                        listBuff(listResult()[0].object());
                        isLoading = false;
                        if (page == undefined || page == 0) {
                            // [ANDROID] [iOS] [BB]
                            if (isAndroid || isiOS || isBB) {
                                applyScrollPager(function callBackLoadMore() {
                                loadOverviewMore(item);
                                });
                            }
                            // [WP]
                            if (isWP) {
                                applyScrollPagerNano(function () {
                                loadOverviewMore(item);
                                });
                            }
                            // [iOS]
                            if (isiOS){
                                /* save to memory */
                                var listTemp = ko.observableArray([]);
                                _.each(listBuff(), function (item) {
                                listTemp.push(item);
                                });

                                var strKey = item.id() + '' + model.cateVM.currentItemId() + model.settingsVM.getLanguageString();
                                overviewListFromSubcategory[strKey] = listTemp();
                            }

                            listNext(listBuff());
                            addToList();
                            hideLoadingDialog();

                            // [ANDROID] [iOS] [BB]
                            if (isAndroid || isiOS || isBB) {
                                setTimeout(function applyScroll() {
                                    myScrollPager.refresh();
                                }, 200);
                            }
                            // [WP]
                            if (isWP) {
                                setTimeout(function () {
                                applyAfterFillDataNano();
                                }, 200);
                            }	
                            } else {
                            var listBuffLength = listBuff().length;
                            for (var i = 0; i < listBuffLength; i++) {
                                listNext.push(listBuff.shift());
                            }
                        }
                    }
					
				}
			}).done(function () {
				CheckExpireSession(
					listResult,
					false,
					function() {
						getByCategory(item, page);
					}, 
					function(entityResult) {
                        listBuff(entityResult());
						if (page == undefined || page == 0) {
							// [ANDROID] [iOS] [BB]
							if (isAndroid || isiOS || isBB) {
								applyScrollPager(function callBackLoadMore() {
									loadOverviewMore(item);
								});						
							}
							// [WP]
							if (isWP) {
								applyScrollPagerNano(function () {
									loadOverviewMore(item);
								});
							}		
                           // [iOS]
                           if (isiOS){
                               /* save to memory */
                               var listTemp = ko.observableArray([]);
                               _.each(entityResult(), function (item) {
                                      listTemp.push(item);
                                      });
                               
                               var strKey = item.id() + '' + model.cateVM.currentItemId() + model.settingsVM.getLanguageString();
                               overviewListFromSubcategory[strKey] = listTemp();
                           }
							listNext(entityResult());
							addToList();
							hideLoadingDialog();

							// [ANDROID] [iOS] [BB]
							if (isAndroid || isiOS || isBB) {
								setTimeout(function applyScroll() {
									myScrollPager.refresh();
								}, 200);
							}
							// [WP]
							if (isWP) {
								setTimeout(function () {
									applyAfterFillDataNano();
								}, 200);
							}	
						} else {
							var listBuffLength = entityResult().length;
							for (var i = 0; i < listBuffLength; i++) {
								listNext.push(entityResult.shift());
							}
						}
					});
			}).fail(function (e) {
                    CheckExpireSessionErrorCallback(e,
                                                    function(){
                                                    /* session expired */
                                                    getByCategory(item, page);
                                                    },
                                                    function(){
                                                    /* not expire */
                                                    });
			});
		},

		// [ENHANCE] The same with getByCategory (exclude: API function, file storage)
		getNewestForStartPage = function (page, item) {
			title(item.title());
            currentItem = null;
			var maxPageNumberTemp = maxPageNumber;
			if (page == undefined || page == 0) {
				page = 0;
				maxPageNumberTemp = maxPageNumber * pageBufferNumber;
				list([]);
				listNext([]);
				listPrev([]);
                // [iOS]
                if (isiOS){
                    var strKey = item.id() + model.settingsVM.getLanguageString();
                    if (overviewListFromSubcategory[strKey] != undefined) {
                        
                        var listTemp = ko.observableArray(overviewListFromSubcategory[strKey]);
                        _.each(listTemp(), function (i) {
                               listNext.push(i);
                               });
                        addToList(list, listNext);
                        applyScrollPager(function callBackLoadMore() {
                                         loadNewestStartPageMore(item);
                                         });
                        // setTimeout(function applyScroll(){myScroll.refresh();}, 5000);
                        return;
                    }
                }
				showLoadingDialog();
			}
			listBuff([]);
            var listResult = ko.observableArray([]);
			isLoading = true;
			datacontext.overviewStartPage.getNewestStartPage({
				results: listResult,
				key: 'saveFilesearch_newest' + item.id() + '' + model.settingsVM.getLanguageString() + '_' + page + '_' + maxPageNumber,
				listId: item.id(),
				page: page,
				maxPage: maxPageNumberTemp,
				callbackFunc: function () {
					/* get data from local store */
                    if (listResult().length > 0){
                        listBuff(listResult()[0].object());
                        hideLoadingDialog();
                        isLoading = false;
                        if (page == undefined || page == 0) {
                        // [ANDROID] [iOS] [BB]
                        if (isAndroid || isiOS || isBB) {
                        applyScrollPager(function callBackLoadMore() {
                        loadNewestStartPageMore(item);
                        });
                        }
                        // [WP]
                        if (isWP) {
                        applyScrollPagerNano(function () {
                        loadNewestStartPageMore(item);
                        });
                        }
                        // [iOS]
                        if (isiOS){
                        /* save to memory */
                        var listTemp = ko.observableArray([]);
                        _.each(listBuff(), function (item) {
                        listTemp.push(item);
                        });

                        var strKey = item.id() + model.settingsVM.getLanguageString();
                        overviewListFromSubcategory[strKey] = listTemp();
                        }
                        listNext(listBuff());
                        addToList();
                        hideLoadingDialog();

                        // [ANDROID] [iOS] [BB]
                        if (isAndroid || isiOS || isBB) {
                        setTimeout(function applyScroll() {
                        myScrollPager.refresh();
                        }, 200);
                        }
                        // [WP]
                        if (isWP) {
                        setTimeout(function () {
                        applyAfterFillDataNano();
                        }, 200);
                        }	
                        } else {
                        var listBuffLength = listBuff().length;
                        for (var i = 0; i < listBuffLength; i++) {
                        listNext.push(listBuff.shift());
                        }
                        }
                    }
					
				}				
			}).done(function () {
				CheckExpireSession(
					listResult,
					false,
					function() {
						getNewestForStartPage(page, item);
					}, 
					function(entityResult) {
                        listBuff(entityResult());
						if (page == undefined || page == 0) {
							// [ANDROID] [iOS] [BB]
							if (isAndroid || isiOS || isBB) {
								applyScrollPager(function callBackLoadMore() {
									loadNewestStartPageMore(item);
								});						
							}
							// [WP]
							if (isWP) {
								applyScrollPagerNano(function () {
									loadNewestStartPageMore(item);
								});
							}
                           // [iOS]
                           if (isiOS){
                                   /* save to memory */
                               var listTemp = ko.observableArray([]);
                               _.each(listBuff(), function (item) {
                                      listTemp.push(item);
                                      });
                                   
                               var strKey = item.id() + model.settingsVM.getLanguageString();
                               overviewListFromSubcategory[strKey] = listTemp();
                           }
                                   
							listNext(listBuff());
							addToList();

							// [ANDROID] [iOS] [BB]
							if (isAndroid || isiOS || isBB) {
								setTimeout(function applyScroll() {
									myScrollPager.refresh();
								}, 200);
							}
							// [WP]
							if (isWP) {
								setTimeout(function () {
									applyAfterFillDataNano();
								}, 200);
							}
                           hideLoadingDialog();
                           isLoading = false;
						} else {
							var listBuffLength = listBuff().length;
							for (var i = 0; i < listBuffLength; i++) {
								listNext.push(listBuff.shift());
							}
						}
                                   
					});
			}).fail(function (e) {
                    CheckExpireSessionErrorCallback(e,
                                                    function(){
                                                    /* session expired */
                                                    getNewestForStartPage(page, item);
                                                    },
                                                    function(){
                                                    /* not expire */
                                                    });
			});
		},

		// Move (maxPageNumber) items from listNext to list
		addToList = function () {
			var length = listNext().length;
			var listTemp = ko.observableArray([]);
			length = length > maxPageNumber ? maxPageNumber : length;
			for (var i = 0; i < length; i++) {
				listTemp.push(listNext.shift());
			}
			list(listTemp());
		},

		// [ENHANCE] move Favorite functions to vm.favorite.js
		getFavoriteByFolder = function () {
		if (!CanLoad())
				return;
		    //$('#popupSelectFolder').popup("open");
            $('#popupSelectFolder-main').css('display', 'block');
            model.bookVM.applyIscrollForFolder('wrapper_scroll_folder_favorite_view');
            stackViews.push(strSelectFolder);
		},
        closeFolderPopup = function(){
        if (!CanLoad())
				return;
            $('#popupSelectFolder-main').css('display', 'none');
//            $('#popupSelectFolder').popup("close");
			popFromStack(stackViews, strSelectFolder);	
        },
		// Get local data to display
		getFavorite = function (timeDelay) {
			currentItem = null;
			showLoadingDialog();
			setTimeout(function () {
				title(getLocalizeText('favorites'));
				list([]);
				listNext([]);
				listPrev([]);
				listFavorite([]);
				var overViewsJSON = localStore.get(bookVM.FavoriteFolder());
				if (overViewsJSON != null) {
					var overViews = JSON.parse("[" + overViewsJSON + "]");
					_.each(overViews, function (i) {
						var item = new BookModel();
						item.overView.dataId(i.dataId);
						item.overView.title(i.title);
						if (i.thumbnailMedium != undefined && i.thumbnailMedium.length > 0) {
							item.overView.thumbnailMedium(i.thumbnailMedium);
							localStore.choosePath(item.overView.thumbnailMediumDisplay, i.thumbnailMedium);
						} else {
							item.overView.thumbnailMedium(i.thumbnail);
							localStore.choosePath(item.overView.thumbnailMediumDisplay, i.thumbnail);
						}
						item.overView.author(i.author);
						item.overView.extraText(i.extraText);
						item.overView.subExtraText(i.subExtraText);
						if (i.status == undefined || i.status != "delete") {
							listNext.push(item);
						} else {
							item.overView.status("delete");
						}
						listFavorite.push(item);
					});
					isLoading = false;
					setTimeout(function () {
						// [ANDROID] [iOS] [BB]
						if (isAndroid || isiOS || isBB)
							applyScrollPager();
						// [WP]
						if (isWP)
							applyScrollPagerNano();

						addToList();

						// [ANDROID] [iOS] [BB]
						if (isAndroid || isiOS || isBB) {
							setTimeout(function applyScroll() {
								myScrollPager.refresh();
								hideLoadingDialog();
							}, 100);
						}
						// [WP]
						if (isWP) {
							setTimeout(function () {
								applyAfterFillDataNano();
								hideLoadingDialog();
							}, 200);
						}
					}, 100);
				} else {
					hideLoadingDialog();
				}
			}, timeDelay);
		},

		// Get favorite book items
		// [ENHANCE] check download book items
		syncFavorite = function () {
			if (!CanLoad())
				return;

			if (isLogin) {
				var listTemp = ko.observableArray([]);
				title(getLocalizeText('favorites'));
				isLoading = true;
				showLoadingDialog();

				localStore.save('favorite_folders', null);

				model.favoriteVM.getFolders(true);
                
				return datacontext.syncFavorite.get({
					results: listTemp
				}).done(function () {
					CheckExpireSession(
						listTemp, 
						false,
						function() {
							isUserActionClick = false;
							syncFavorite();
						}, 
						function(entity) {
							if (entity().length > 0) {
								// need delete all favorites before download
								clearAllFavorite();
								var arrayItem = entity();
								getDetailInFavorite(arrayItem, 0);
							}
							else{
								/* favorite is empty */
                                stopLoading();
							}
						});
				}).fail(function (e) {
                        CheckExpireSessionErrorCallback(e,
                                                        function(){
                                                        /* session expired */
                                                        isUserActionClick = false;
                                                        syncFavorite();
                                                        },
                                                        function(){
                                                        /* not expire */
                                                        });
				});
			}
		},

		/* use recursive to get each favorite detail */
		getDetailInFavorite = function (arrayItem, index) {
			/* exit condition */
			title(index + '/' + arrayItem.length);
			if (index >= arrayItem.length) {
				localStore.save("is_first_sync_favorite", "false");
				isUserActionClick = false;
				model.viewFavorite(1000);
				return;
			}
			var favoriteItem = arrayItem[index];
			var item = ko.observableArray([]);
			var entityTemp = new ko.observable();
			datacontext.book.getDetail({
				results: item,
				callbackFunc: function () {
					try {
						var itemTemp = item()[0].object;
						saveFavoriteOnLocal(favoriteItem.folderID(), favoriteItem.itemID(), itemTemp);
					} catch (e) {}
					index++;
					getDetailInFavorite(arrayItem, index);
				},
                noLogging: true,
				id: favoriteItem.itemID(),
				key: "saveFilebookDetail_" + systemLanguage + '' + favoriteItem.itemID()
			}).done(function () {
				if (item != undefined && item().length > 0) {
					/* have data return from server */
                    entityTemp(item()[0]);
					if (entityTemp().responseCode() != 0) {
						/* get error from server */
					} else {
						/* cap API success */
						try {
							var itemTemp = entityTemp().object;
							saveFavoriteOnLocal(favoriteItem.folderID(), favoriteItem.itemID(), itemTemp);
						} catch (e) {}
					}
					index++;
					getDetailInFavorite(arrayItem, index);
				} else {
					/* fail */
				}
			}).fail(function (e) {
                    CheckExpireSessionErrorCallback(e,
                                                    function(){
                                                    /* session expired */
                                                    getDetailInFavorite(arrayItem, index);
                                                    },
                                                    function(){
                                                        /* not expire */
                                                        index++;
                                                        getDetailInFavorite(arrayItem, index);
                                                    });
				
			});
		},

		// Delete local storage for favorite book items
		clearAllFavorite = function () {
			for (var i = 0; i < favoriteVM.folders().length; i++) {
				var overViewsJSON = localStore.get("Folder_" + favoriteVM.folders()[i].folderID());
				if (overViewsJSON != null) {
					var overViews = JSON.parse("[" + overViewsJSON + "]");
					_.each(overViews, function (item) {
						localStore.removeItem("Favorite_book_id_" + item.dataId);
					});
					localStore.removeItem("Folder_" + favoriteVM.folders()[i].folderID());
				}
			}
		},

		// Store favorite book items
		saveFavoriteOnLocal = function (strFolderID, itemID, item) {
			var folder = "Folder_" + strFolderID;
			item.overView.dataId = itemID;
			localStore.save("Favorite_book_id_" + item.overView.dataId, true);
			// [DONE]
			SaveBookToLocal(folder, itemID, item.overView);
		},

		// Show/Hide delete button in favorite list
		editFavorite = function () {
			isEditing(!isEditing());
			if (currentFavoriteItem != null) {
				currentFavoriteItem.overView.isPrepareDelete(false);
				currentFavoriteItem = null;
			}
		},

		// Handle select folder
		selectFolder = function (item) {
			folderID(item.folderID);
			localStore.save("current_favorite_folder_id", item.folderID());
			bookVM.FavoriteFolder("Folder_" + item.folderID());
			bookVM.FavoriteFolderLabel(item.folderName());
			getFavorite(10);
			$('#popupSelectFolder').popup("close");
            $('#popupSelectFolder-main').css('display', 'none');
			myScroll.refresh();
		},

		// Show message to confirm when click delete favorite book item
		deleteFavorite = function (item) {
			if (!CanLoad())
				return;
			if (currentFavoriteItem != null) {
				currentFavoriteItem.overView.isPrepareDelete(false);
			}
			currentFavoriteItem = item;
			item.overView.isPrepareDelete(true);
		},

		deleteFavoriteNo = function (item) {
			if (!CanLoad())
				return;
			item.overView.isPrepareDelete(false);
			currentFavoriteItem = null;
		},

		// Handle delete favorite and refresh list
		deleteFavoriteYes = function (item) {
			if (!CanLoad())
				return;
            item.overView.isPrepareDelete(false);
            var listTemp = ko.observableArray([]);
            showLoadingDialog();
            isLoading = true;

            return datacontext.editFavorite.remove({
                results: listTemp,
                folder_id: folderID(),
                data_id: item.overView.dataId()
            }).done(function () {
                    if (listTemp().length > 0){
                        CheckExpireSession(
                            listTemp, 
                            true,
                            function() {
                                isUserActionClick = false;
                                deleteFavoriteYes(item);
                            }, 
                            function(entityResult) {
                                deleteFromLocal(item);
                            });
                    }
                    else{
                        ShowErrorMessage();
                    }
            }).fail(function (e) {
                    CheckExpireSessionErrorCallback(e,
                                                    function(){
                                                    /* session expired */
                                                    isUserActionClick = false;
                                                    deleteFavoriteYes(item);
                                                    },
                                                    function(){
                                                    /* not expire */
                                                    
                                                    });
            });
			
		},

		// Delete favorite book item from local storage
		deleteFromLocal = function (item) {
			showPopup(getLocalizeText('deleteFavoriteSuccessfull'));
			var overViewsJSON = "";
			_.each(listFavorite(), function (i) {
				if (i.overView.dataId() == item.overView.dataId()) {
					localStore.removeItem("Favorite_book_id_" + i.overView.dataId());
					i.overView.status("delete");
				}
				overViewsJSON = overViewsJSON + ko.toJSON(i.overView) + ",";
			});
			localStore.save(bookVM.FavoriteFolder(), overViewsJSON.substring(0, (overViewsJSON.length - 1)));
			list.remove(function (i) {
				if (i.overView.dataId() == item.overView.dataId()) {
					setTimeout(function applyScroll() {
						myScroll.refresh();
					}, 200);
					return true;
				}
			});
		},
    
		// Book detail view
		viewBook = function (item) {
			if (isJqmGhostClick()) {
				return;
			}
            
            model.overviewVM.gotoBookDetail(item, function(callback) {
                                            overviewBookbyZoomInAnimation(callback, item);
                                            });
            
            
		},
        gotoBookDetail = function(item, overrideView){
			model.isNeedBackButtonAnimation(true);
			model.cateVM.listnext([]);
			stackViews.push(strOverview);
			model.applyScrollF();
			
            if (!overrideView || (typeof overrideView) != 'function'){
                /* is not call from start page */
                model.startpageVM.isDisplayStartPage(false);
            }
			// Remove delete stage in Favorite book items
			if (currentFavoriteItem != null) {
				currentFavoriteItem.overView.isPrepareDelete(false);
				currentFavoriteItem = null;
			}
		    
			bookVM.getDetail(item.overView.dataId(), false, function (isSuccess) {
                             if (isSuccess){
                                 if (bookVM.entity() != undefined) {
                                     if (item.overView.thumbnailMedium() != undefined && item.overView.thumbnailMedium().length > 0){
                                            bookVM.entity().overView.thumbnailMedium(item.overView.thumbnailMedium());
                                     }
                                     if (item.overView.thumbnailMediumDisplay() != undefined && item.overView.thumbnailMediumDisplay().length > 0){
                                            bookVM.entity().overView.thumbnailMediumDisplay(item.overView.thumbnailMediumDisplay());
                                     }
                                 }
                                 if (overrideView && (typeof overrideView) == 'function'){
                                 /* is call from start page */
                                 overrideView(function () {
                                              isDisplayOverView(false);
                                              if (funcViewBook != undefined) {
                                              funcViewBook();
                                              }
                                              
                                              model.startpageVM.isDisplayStartPage(false);
                                              setTimeout(function () {
                                                         myScroll.refresh();
                                                         model.bookVM.setTextColorDefault();
                                                         }, 200);
                                              
                                              });
                                 
                                 }
                             }
                             
                             });
            
        },
    
        overviewBookbyZoomInAnimation = function(callback, item) {
            var topOffSet = $('#' +item.overView.dataId()+'id').offset().top;
            
            var animationDurion = 1000;
            var widthOfScreen = window.innerWidth;
            var	heightOfScreen = window.innerHeight;
            
            if (isiOS){
            	/* is iOS, animation smooth than other, so it set time to smaller */
            	animationDurion = 500;
            }
            
            var zoom = $('#zoomItem'),
            cover = $('#coverItem');
            
            cover.css('left', '15px');
            cover.css('top', topOffSet + 5 + 'px');
            cover.css('width', '46px');
            cover.css('height', '69px');
            
            $($('img', cover)[0]).attr('src', item.overView.thumbnailMediumDisplay());
            $('.coverItem img').css('width', '46px');
            $('.coverItem img').css('height', '69px');
            
            zoom.css('width', '46px');
            zoom.css('height', '69px');
            zoom.css('left', '15px');
            zoom.css('top', topOffSet + 5 + 'px');
            
            /* keep current item for zoom out fuction */
            currentLeft = 15;
            currentTop = topOffSet + 5;
            currentWidth = 46;
            currentHeight = 69;
            currentImg = item.overView.thumbnailMediumDisplay();
            
            zoom.show();
            cover.show();
            
            setTimeout(function(){
                       zoom.animate({
                                    top: '44px',
                                    left: '0px',
                                    width: widthOfScreen + 'px',
                                    height: heightOfScreen - 52 - 44 + 'px'
                                    }, animationDurion, function () {
                                    callback();
                                    zoom.hide();
                                    });}, 100);
            setTimeout(function(){
                       cover.animate({
                                     top: '59px',
                                     left: '15px',
                                     width: '92px',
                                     height: '138px'
                                     }, animationDurion, function () {
                                     cover.hide();
                                     });}, 100);
            setTimeout(function(){
                       $('img', cover).animate({
                                               width: '92px',
                                               height: '138px'
                                               }, animationDurion, function () {
                                               
                                               });}, 100);
            
            
        },
        overviewBookbyZoomOutAnimation = function(callback) {
            var detailImageOffset = $('#detail-image').offset();
            
            var animationDurion = 1000;
            var widthOfScreen = window.innerWidth;
            var	heightOfScreen = window.innerHeight;
            
            if (isiOS){
            	/* is iOS, animation smooth than other, so it set time to smaller */
            	animationDurion = 500;
            }
            
            var zoom = $('#zoomItem'),
            cover = $('#coverItem');
            
            cover.css('left', detailImageOffset.left + 'px');
            cover.css('top', detailImageOffset.top + 'px');
            cover.css('width', '92px');
            cover.css('height', '138px');
            
            $($('img', cover)[0]).attr('src', currentImg);
            
            $('.coverItem img').css('width', '92px');
            $('.coverItem img').css('height', '138px');
            
            zoom.css('width', widthOfScreen + 'px');
            zoom.css('height', heightOfScreen - 52 - 44 + 'px');
            zoom.css('left', '0px');
            zoom.css('top', '44px');
            
            zoom.show();
            cover.show();
            callback()
            
            setTimeout(function(){
                       zoom.animate({
                                    top: currentTop + 'px',
                                    left: currentLeft + 'px',
                                    width: '46px',
                                    height: '69px'
                                    }, animationDurion, function () {
                                    zoom.hide();
                                    });}, 100);
            setTimeout(function(){
                       cover.animate({
                                     top: currentTop + 'px',
                                     left: currentLeft + 'px',
                                     width: '46px',
                                     height: '69px'
                                     }, animationDurion, function () {
                                     cover.hide();
                                     });}, 100);
            setTimeout(function(){
                       $('img', cover).animate({
                                               width: '46px',
                                               height: '69px'
                                               }, animationDurion, function () {
                                               
                                               });}, 100);
            
        },
    

		// Add item to top list
		addItemTop = function () {
			if (!isScrollByUser) {
				isScrollByUser = true;
				return;
			}
			var listPrevLength = listPrev().length;
			var currentLength = list().length;
			if (currentLength > maxItemsKeepOnList) {
				if (listPrevLength > 0) {
					listPrevLength = listPrevLength > maxPageNumber ? maxPageNumber : listPrevLength;
					var removeListNumber = 0;
					for (var i = 0; i < maxPageNumber; i++) {
						if (i < listPrevLength) {
							removeListNumber++;
							list.unshift(listPrev.pop());
						}
						if (i < currentLength) {
							listNext.unshift(list.pop());
						}
					}
				    // [iOS] [BB] [Android]
					if (isiOS || isBB || isAndroid) {
					    myScrollPager.refresh();
					    isScrollByUser = false;
					    var scrollToItem = removeListNumber + 1;
					    myScrollPager.scrollToElement('li:nth-child(' + scrollToItem + ')', 1);
					}
				    // [WP]
					if (isWP) {
					    setTimeout(function () {
					        applyAfterFillDataNano();
					    }, 200);
					}

				}
			}
		},

		// Add item to bottom
		addItemBottom = function () {
			if (!isScrollByUser) {
				isScrollByUser = true;
				return;
			}
			var listNextLength = listNext().length;
			var currentLength = list().length;
			if (listNextLength > 0) {
				listNextLength = listNextLength > maxPageNumber ? maxPageNumber : listNextLength;
				var removeListNumber = 0;
				for (var i = 0; i < maxPageNumber; i++) {
					if (i < listNextLength) {
						list.push(listNext.shift());
					}
					if (currentLength > maxItemsKeepOnList) {
						if (i < currentLength) {
							removeListNumber++;
							listPrev.push(list.shift());
						}
					}
				}
			    // [iOS] [BB] [Android]
				if (isiOS || isBB || isAndroid) {
				    myScrollPager.refresh();
				    isScrollByUser = false;
				    if (removeListNumber > 0) {
				        var numberOfItemInSreen = Math.round((model.bookVM.heightOfScreen() - 44 - 51) / 80 - 0.5) - 1;
				        var scrollToItem = currentLength - numberOfItemInSreen - removeListNumber;
				        myScrollPager.scrollToElement('li:nth-child(' + scrollToItem + ')', 1);
				    }
				}
			    // [WP]
				if (isWP) {
				    setTimeout(function () {
				        applyAfterFillDataNano();
				    }, 200);
				}
			}
		},

		back = function () {
			window.history.go(-1);
		},

		// Callback for paging in overview
		//	+ item: current category
		loadOverviewMore = function (item) {
			if (item == undefined) {
				if (currentItem == undefined) {
					return;
				}
				item = currentItem;
			}
			var itemCount = list().length + listNext().length + listPrev().length;
			if (itemCount % maxPageNumber == 0 && itemCount / maxPageNumber > pageBufferNumber - 1) {
			    
				/* can get next */
			    page = itemCount / maxPageNumber;
				getByCategory(item, page);
			}
		},

		// Callback for paging in start page
		loadNewestStartPageMore = function (item) {
            if (item == undefined){
                return;
            }
			var itemCount = list().length + listNext().length + listPrev().length;
			if (itemCount % maxPageNumber == 0 && itemCount / maxPageNumber > pageBufferNumber - 1) {
				/* can get next */
				page = itemCount / maxPageNumber;
				getNewestForStartPage(page, item);
			}
		};
		
	return {
		list: list,
        listAnimation: listAnimation,
		getByKey: getByKey,
		getByCategory: getByCategory,
		getNewestForStartPage: getNewestForStartPage,
		getFavorite: getFavorite,
		getFavoriteByFolder: getFavoriteByFolder,
        closeFolderPopup: closeFolderPopup,
		selectFolder: selectFolder,
		syncFavorite: syncFavorite,
		editFavorite: editFavorite,
		deleteFavorite: deleteFavorite,
		addItemTop: addItemTop,
		addItemBottom: addItemBottom,
		keySearch: keySearch,
		applyScrollPager: applyScrollPager,
		back: back,
		isEditing: isEditing,
		folderID: folderID,
		title: title,
		areYouSureDelete: areYouSureDelete,
		strEdit: strEdit,
		strDone: strDone,
		deleteFavoriteYes: deleteFavoriteYes,
		deleteFavoriteNo: deleteFavoriteNo,
		viewBook: viewBook,
		loadOverviewMore: loadOverviewMore,
		isDisplayOverView: isDisplayOverView,
        gotoBookDetail: gotoBookDetail,
        overviewBookbyZoomOutAnimation: overviewBookbyZoomOutAnimation
	};
}
